package com.oly.cms.hand.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.alibaba.fastjson2.JSONObject;
import com.grace.common.constant.CacheConstants;
import com.grace.common.core.domain.AjaxResult;
import com.grace.common.utils.StringUtils;
import com.grace.redis.utils.RedisCache;

/**
 * 自定义拦截器类
 * 
 * @author 止戈
 * 
 *         实现HandlerInterceptor接口
 * 
 */
@Component
public class CodeInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisCache redisCache;

    /**
     * 访问控制器方法前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String thirdCode = request.getParameter("thirdCode");
        String uuid = request.getParameter("thirdUuid");
        String email = request.getParameter("email");
        String verifyKey = CacheConstants.THIRD_CODE_KEY + StringUtils.nvl(uuid + "_" + email, "");
        String cacheCode = redisCache.getCacheObject(verifyKey);
        if (cacheCode == null) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error("验证码已经过期,请稍后重新获取")));
            response.getWriter().flush();
            return false;
        }
        if (!thirdCode.equalsIgnoreCase(cacheCode)) {
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(AjaxResult.error("验证码已经错误,请检查")));
            response.getWriter().flush();
            return false;
        }
        return true;
    }

}
